package Control;

import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.*;
import java.util.ArrayList;
import java.util.Date;
import java.text.DecimalFormat;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.DefaultTableModel;

import Database.*;
import Model.*;

public class Sales extends JFrame implements ActionListener
{
	private JButton search, clear, cart, remove, sell;
	private JLabel jlID, jlSearch, jlQty, total;
	private JTextField jtID, jtSearch, jtQty, jtTotal;
	private JTextArea purchaseItems;
	private JPanel logo, leftPanel, rightPanel;
	private TableOperations to;
	private int qty, subtotal, cash;
	private SalesAssistant sa;
	private JTable prods, cartList;
	private DefaultTableModel jtM1, jtM2;
	private ArrayList<Product> products = new ArrayList<Product>();
	private ArrayList<Product> cartProd = new ArrayList<Product>();
	private ArrayList<Integer> quantity = new ArrayList<Integer>();
	private ArrayList<Double> price = new ArrayList<Double>();
	private Product toBeSold, inCartList;
	private double totalPrice = 0;
	private DecimalFormat df = new DecimalFormat("#.00");
	private ImageIcon icon = new ImageIcon("frameIcon.png");

	public Sales(SalesAssistant salesA, TableOperations to)
	{
		sa = salesA;
		GridBagLayout layout = new GridBagLayout();
		GridBagConstraints gc = new GridBagConstraints();

		setIconImage(icon.getImage());
		setTitle("MDL - Sale");
		setSize(750, 400);
		setLocationRelativeTo(null);
		setResizable(false);
		setDefaultCloseOperation(DISPOSE_ON_CLOSE);
		this.setLayout(new GridLayout(1, 2));
		this.to = to;

		Insets insets = new Insets(15, 15, 13, 3);

		// leftPanel
		leftPanel = new JPanel();
		leftPanel.setLayout(layout);

		jlID = new JLabel("Card ID");
		gc.gridx = 0;
		gc.gridy = 0;
		gc.weighty = 0;
		gc.weightx = 0;
		gc.insets = insets;
		gc.fill = GridBagConstraints.BOTH;
		leftPanel.add(jlID, gc);

		jtID = new JTextField(10);
		gc.gridx = 1;
		gc.gridy = 0;
		gc.weighty = 0;
		gc.weightx = 2;
		insets = new Insets(15, -35, 13, 15);
		gc.insets = insets;
		gc.fill = GridBagConstraints.BOTH;
		leftPanel.add(jtID, gc);

		jlSearch = new JLabel("Search");
		gc.gridx = 0;
		gc.gridy = 1;
		gc.weighty = 0;
		gc.weightx = 0;
		insets = new Insets(15, 5, 13, 3);
		gc.insets = insets;
		gc.fill = GridBagConstraints.BOTH;
		leftPanel.add(jlSearch, gc);

		jtSearch = new JTextField(10);
		gc.gridx = 1;
		gc.gridy = 1;
		gc.weighty = 0;
		gc.weightx = 2;
		insets = new Insets(15, -35, 13, 15);
		gc.insets = insets;
		gc.fill = GridBagConstraints.BOTH;
		leftPanel.add(jtSearch, gc);

		search = new JButton("Search");
		search.addActionListener(this);
		gc.gridx = 1;
		gc.gridy = 3;
		gc.weighty = 0;
		gc.weightx = 1;
		insets = new Insets(0, 25, 15, 110);
		gc.insets = insets;
		gc.fill = GridBagConstraints.BOTH;
		leftPanel.add(search, gc);

		clear = new JButton("Clear");
		clear.addActionListener(this);
		gc.gridx = 1;
		gc.gridy = 3;
		gc.weighty = 0;
		gc.weightx = 1;
		insets = new Insets(0, 150, 15, 15);
		gc.insets = insets;
		gc.fill = GridBagConstraints.BOTH;
		leftPanel.add(clear, gc);

		createTableProducts();
		gc.gridx = 1;
		gc.gridy = 5;
		gc.weighty = 15;
		gc.weightx = 2;
		insets = new Insets(15, -75, 13, 10);
		gc.insets = insets;
		gc.fill = GridBagConstraints.BOTH;
		leftPanel.add(new JScrollPane(prods), gc);

		cart = new JButton("Add to Cart");
		cart.addActionListener(this);
		gc.gridx = 0;
		gc.gridy = 7;
		gc.weighty = 0;
		gc.weightx = 1;
		insets = new Insets(15, 5, 13, 3);
		gc.insets = insets;
		leftPanel.add(cart, gc);

		add(leftPanel);

		// RightPanel
		rightPanel = new JPanel();
		rightPanel.setLayout(layout);

		gc.gridx = 1;
		gc.gridy = 3;
		gc.weighty = 1;
		gc.weightx = 1;
		insets = new Insets(0, 165, 0, 0);
		gc.insets = insets;
		gc.fill = GridBagConstraints.BOTH;
		rightPanel.add(new JLabel("Cart List"), gc);

		createTableCartList();
		gc.gridx = 1;
		gc.gridy = 5;
		gc.weighty = 15;
		gc.weightx = 2;
		insets = new Insets(5, -10, 0, 13);
		gc.insets = insets;
		gc.fill = GridBagConstraints.BOTH;
		rightPanel.add(new JScrollPane(cartList), gc);

		total = new JLabel("Total");
		gc.gridx = 1;
		gc.gridy = 6;
		gc.weighty = 0;
		gc.weightx = 1;
		insets = new Insets(15, 165, 13, 0);
		gc.insets = insets;
		gc.fill = GridBagConstraints.BOTH;
		rightPanel.add(total, gc);

		jtTotal = new JTextField();
		jtTotal.setEditable(false);
		gc.gridx = 1;
		gc.gridy = 6;
		gc.weighty = 0;
		gc.weightx = 20;
		insets = new Insets(15, 200, 13, 15);
		gc.insets = insets;
		gc.fill = GridBagConstraints.BOTH;
		rightPanel.add(jtTotal, gc);

		remove = new JButton("Remove");
		remove.addActionListener(this);
		gc.gridx = 1;
		gc.gridy = 7;
		gc.weighty = 0;
		gc.weightx = 1;
		insets = new Insets(15, 250, 13, 25);
		gc.insets = insets;
		gc.fill = GridBagConstraints.BOTH;
		rightPanel.add(remove, gc);

		sell = new JButton("Sell");
		sell.addActionListener(this);
		gc.gridx = 1;
		gc.gridy = 7;
		gc.weighty = 0;
		gc.weightx = 1;
		insets = new Insets(15, 25, 13, 200);
		gc.insets = insets;
		rightPanel.add(sell, gc);

		gc.gridx = 3;
		gc.gridy = 2;
		gc.weighty = 1;
		gc.weightx = 1;
		this.add(rightPanel, gc);
	}

	public void createTableProducts()
	{
		jtM1 = new DefaultTableModel();
		jtM1.addColumn("Product Name");

		fillTable1();

		prods = new JTable(jtM1);
		prods.addMouseListener(new MouseAdapter()
		{
			public void mousePressed(MouseEvent e)
			{
				int row = prods.getSelectedRow();
				int productID = products.get(row).getId();
				String desc = products.get(row).getDescription();
				double cost = products.get(row).getCost();
				double price = products.get(row).getPrice();
				int qty = products.get(row).getQty();
				int reorder = products.get(row).getReorder();
				int supplierID = products.get(row).getSupplierID();
				int reorderAmount = products.get(row).getrAmount();
				java.sql.Date sqlDate = products.get(row).getSqlDate();
				toBeSold = new Product(productID, desc, cost, price, sqlDate,
						qty, reorder, reorderAmount, supplierID);
			}
		});
	}

	public void createTableCartList()
	{
		jtM2 = new DefaultTableModel();
		jtM2.addColumn("Products");
		jtM2.addColumn("Price");
		jtM2.addColumn("Quantity");
		jtM2.addColumn("Total");

		fillTable2();

		cartList = new JTable(jtM2);
		cartList.addMouseListener(new MouseAdapter()
		{
			public void mousePressed(MouseEvent e)
			{
				int row = cartList.getSelectedRow();
				int productID = cartProd.get(row).getId();
				String desc = cartProd.get(row).getDescription();
				double cost = cartProd.get(row).getCost();
				double price = cartProd.get(row).getPrice();
				int qty = cartProd.get(row).getQty();
				int reorder = cartProd.get(row).getReorder();
				int supplierID = cartProd.get(row).getSupplierID();
				int reorderAmount = cartProd.get(row).getrAmount();
				java.sql.Date sqlDate = cartProd.get(row).getSqlDate();
				inCartList = new Product(productID, desc, cost, price, sqlDate,
						qty, reorder, reorderAmount, supplierID);
			}
		});
	}

	public void fillTable1()
	{
		for (int i = 0; i < products.size(); i++)
		{
			String[] name =
			{ products.get(i).getDescription() };
			jtM1.addRow(name);
		}
	}

	public void fillTable2()
	{
		if (jtM2.getRowCount() >= 1)
		{
			String[] prodInfo =
			{
					cartProd.get(cartProd.size() - 1).getDescription(),
					Double.toString(cartProd.get(cartProd.size() - 1)
							.getPrice()),
					Integer.toString(quantity.get(quantity.size() - 1)),
					Double.toString(price.get(price.size() - 1)) };
			jtM2.addRow(prodInfo);
		} else
		{
			for (int i = 0; i < cartProd.size(); i++)
			{
				String[] prodInfo =
				{ cartProd.get(i).getDescription(),
						Double.toString(cartProd.get(i).getPrice()),
						Integer.toString(quantity.get(i)),
						Double.toString(price.get(i)) };
				jtM2.addRow(prodInfo);
			}
		}
	}

	public void search()
	{
		try
		{
			if (jtSearch.getText().equals(""))
				JOptionPane.showMessageDialog(null,
						"Please enter product ID or description");
			else
				products.addAll(to.searchProduct(Integer.parseInt(jtSearch
						.getText())));
		} catch (NumberFormatException nfe)
		{
			products.addAll(to.searchProduct(jtSearch.getText()));
		}
		fillTable1();
		if (jtM1.getRowCount() <= 0)
			JOptionPane
					.showMessageDialog(null,
							"Product not found. Hint: Use a CAPITAL LETTER for the 1st Letter");
	}

	public void clear()
	{

		try
		{
			jtM1.removeRow(0);
			for (int i = 0; i < jtM1.getRowCount(); i++)
			{
				jtM1.removeRow(i);
			}

			products.remove(0);
			for (int i = 0; i < products.size(); i++)
			{
				products.remove(i);
			}
		} catch (Exception e)
		{
			System.out.println("No rows to be deleted");
		} finally
		{
			jtSearch.setText("");
		}
	}

	public void removeItem()
	{
		try
		{
			int index = cartList.getSelectedRow();
			totalPrice -= price.get(index);
			cartProd.remove(index);
			price.remove(index);
			quantity.remove(index);
			jtM2.removeRow(index);
			jtTotal.setText("€" + df.format(totalPrice));
		} catch (Exception e)
		{
			System.out.println("No rows to be deleted" + e);
		}
	}

	public void actionPerformed(ActionEvent e) throws NumberFormatException
	{
		try
		{
			if (e.getSource() == search)
			{
				if (jtM1.getRowCount() > 0)
				{
					clear();
					search();
				} else
					search();
			} else if (e.getSource() == clear)
				clear();
			else if (e.getSource() == remove)
				removeItem();
			else if (e.getSource() == cart)
			{
				boolean cont;
				do
				{
					qty = Integer.parseInt(JOptionPane.showInputDialog("Quantity", JOptionPane.INFORMATION_MESSAGE));
					if (qty <= 0)
					{
						JOptionPane.showMessageDialog(null,
								"Cannot enter negative numbers");
						cont = false;
					} else
					{
						qty = to.checkStock(toBeSold, qty);
						cont = true;
						price.add(toBeSold.getPrice() * qty);
						quantity.add(qty);
						cartProd.add(toBeSold);
						fillTable2();
						totalPrice += price.get(price.size() - 1);
						jtTotal.setText(df.format(totalPrice));
						clear();

					}
				} while (cont == false);
			} else if (e.getSource() == sell)
			{
				Product[] p = new Product[cartProd.size()];
				int[] qty = new int[quantity.size()];
				for (int i = 0; i < p.length; i++)
				{
					p[i] = cartProd.get(i);
					qty[i] = quantity.get(i);

				}
				if (jtID.getText().equals(""))
				{
					// non-loyalty sale
					double cash = 0;
					jtTotal.setText(Double.toString(to.sellStock(p, qty, sa)));
					while (cash < totalPrice)
					{
						cash = Double.parseDouble(JOptionPane
								.showInputDialog("Enter Amount"));
						if (cash < totalPrice)
							JOptionPane.showMessageDialog(null,
									"Insufficient cash");
					}
					Receipt r = new Receipt(totalPrice, cash);
					r.setVisible(true);
					this.dispose();
				} else
				{
					// loyalty sale
					double cash = 0;
					LoyaltyCustomer c = to.searchCustomer(
							Integer.parseInt(jtID.getText())).get(0);
					totalPrice = to.sellStock(p, qty, c, sa);
					while (cash < totalPrice)
					{
						cash = Double.parseDouble(JOptionPane
								.showInputDialog("Enter Amount"));
						if (cash < totalPrice)
							JOptionPane.showMessageDialog(null,
									"Insufficient cash");
					}
					Receipt r = new Receipt(totalPrice, cash);
					r.setVisible(true);
					this.dispose();
				}
			}
		} catch (NullPointerException npe)
		{
			JOptionPane.showMessageDialog(null, "Sale Cancelled");
		} catch (NumberFormatException nfe)
		{
			JOptionPane.showMessageDialog(null, "Add to Cart cancelled");
		}
	}
}